// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request-promise');
const xml2js = require('xml2js');
const fs = require("fs");
const crypto = require('crypto');//签名和验证、加密和解密

// 商户证书路径
const cert_path = './zhengshu/apiclient_cert.pem';
const key_path = './zhengshu/apiclient_key.pem';

// 使用当前云环境
cloud.init({
    env: 'tfjkp-0ge80vu9ea710148'
})

// 生成签名
function createSign(params, key) {
    console.log("sign生成的时候所需的参数：",params)
    // .filter(k => params[k]) 非空过滤，如果不存在非空参数，建议不使用，避免sign生成出现问题
    let stringA = Object.keys(params).sort().map(k => `${k}=${params[k]}`).join('&') + '&key=' + key;
    console.log('原始字符串sign：', stringA)
    let sign = crypto.createHash('md5').update(stringA, 'utf8').digest('hex').toUpperCase();
    console.log('MD5加密后的sign：', sign)
    return sign;
}

// 构建请求数据
function buildRequestData(options) {
    const params = {
        mch_appid: options.mch_appid,
        mchid: options.mchid,
        // device_info: options.device_info || '',
        nonce_str: options.nonce_str || '',
        sign: createSign({
            mch_appid: options.mch_appid,
            mchid: options.mchid,
            // device_info: options.device_info,
            nonce_str: options.nonce_str,
            partner_trade_no: options.partner_trade_no,
            openid: options.openid,
            check_name: options.check_name,
            re_user_name: options.re_user_name,
            amount: options.amount,
            desc: options.desc,
            spbill_create_ip: options.spbill_create_ip,
        }, options.key),
        partner_trade_no: options.partner_trade_no,
        openid: options.openid,
        check_name: options.check_name,
        re_user_name: options.re_user_name,
        amount: options.amount,
        desc: options.desc,
        spbill_create_ip: options.spbill_create_ip,
    };
    return `<xml>${Object.keys(params).map(key => `<${key}>${params[key]}</${key}>`).join('')}</xml>`;
}

// 发起付款请求
async function sendPayment(options) {
    const payload = buildRequestData(options);
    console.log('请求接口的请求体：', payload)
    const url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
    const headers = {
        'Content-Type': 'application/xml',
    };
    try {
        const response = await request.post({
            url,
            body: payload,
            headers,
            key: fs.readFileSync(key_path),
            cert: fs.readFileSync(cert_path)
        });
        const result = await xml2js.parseStringPromise(response, {trim: true, explicitArray: false});
        return result.xml;
    } catch (error) {
        console.error('转账请求错误:', error);
        throw error;
    }
}

// 云函数入口函数
exports.main = async (event, context) => {

    console.log("前端传入的参数：", event)
    const {
        mch_appid,
        mchid,
        key,
        nonce_str,
        partner_trade_no,
        openid,
        check_name,
        re_user_name,
        amount,
        desc,
        spbill_create_ip,
    } = event;


    try {
        const paymentResult = await sendPayment({
            mch_appid,
            mchid,
            key,
            nonce_str,
            partner_trade_no,
            openid,
            check_name,
            re_user_name,
            amount,
            desc,
            spbill_create_ip,
        });

        if (paymentResult.return_code === 'SUCCESS' && paymentResult.result_code === 'SUCCESS') {
            return {
                success: true,
                message: '转账成功',
                data: paymentResult,
            };
        } else {
            return {
                success: false,
                message: `转账失败，失败的用户ID: ${paymentResult.result_code}`,
                data: paymentResult,
            };
        }
    } catch (error) {
        return {
            success: false,
            message: `error: ${error.message}`,
        };
    }
};
